package com.tools.cleanmaster.ui.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tools.ad.util.StatusBarUtil;
import com.tools.cleanmaster.R;
import com.tools.cleanmaster.common.thread.ThreadPool;
import com.tools.cleanmaster.controller.MediaHelper;
import com.tools.cleanmaster.controller.TrashHandler;
import com.tools.cleanmaster.manager.TrashManager;
import com.tools.cleanmaster.model.TrashType;
import com.tools.cleanmaster.model.TrashesData;
import com.tools.cleanmaster.model.item.FileTrashItem;
import com.tools.cleanmaster.model.item.TrashItem;
import com.tools.cleanmaster.model.item.VideoTrashItem;
import com.tools.cleanmaster.ui.adapter.DeepAdapter;
import com.tools.cleanmaster.ui.adapter.VideoLargeFileAdapter;
import com.tools.cleanmaster.ui.card.ui.EmptyLayout;
import com.tools.cleanmaster.ui.dialog.CommonDialog;
import com.tools.cleanmaster.ui.view.ToastHelper;
import com.tools.cleanmaster.ui.view.header.HeadHelper;
import com.tools.cleanmaster.utils.DateTimeUtils;
import com.tools.cleanmaster.utils.MimeTypeUtil;
import com.tools.cleanmaster.utils.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * desc: 展示大文件（如视频）列表
 * date: 2018/7/4 11:41
 * author: ancun
 */
public class VideoLargeFileActivity extends DeepActivity {
    //进入类型
    public static final String TYPE = "type";
    public static final int IMAGE = 0;
    public static final int VIDEO = 1;
    public static final int LARGE = 2;
    private ListView mListView;
    private EmptyLayout mEmptyView;
    private Button mDeleteBtn;
    private VideoLargeFileAdapter mAdapter;
    private int mType = -1;
    private List<TrashItem> trashItems = null;

    private CommonDialog mVideoLargeDialog;
    private TextView mPathText;
    private TextView mSizeText;
    private TextView mTimeText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.video_large_main);
        StatusBarUtil.setTransparentForImageView(this, findViewById(R.id.titlebar));
        StatusBarUtil.setTranslucentForNavigation(this,findViewById(R.id.root));
        init();
        initData();
    }

    private void init() {
        Intent intent = getIntent();
        if (intent != null) {
            mType = intent.getIntExtra(TYPE, -1);
        }

        int titleId = mType == VIDEO ? R.string.trash_clean_video_file : R.string.trash_clean_large_file_title;
        HeadHelper.setupMainHeader(this, R.id.titlebar, titleId, this)
                .hideSettingButton();

        mListView = findViewById(R.id.trash_result_view_lv);
        mEmptyView = findViewById(R.id.empty_view);
        mDeleteBtn = findViewById(R.id.bottom_button);
        mEmptyView.setTips(R.string.trash_clean_empty_summary);
        mListView.setEmptyView(mEmptyView);
        setDeleteButton(mDeleteBtn);
    }

    private void initData() {
        TrashHandler trashHandler = TrashManager.getInstance().getTrashHandler(true);
        if (trashHandler == null) {
            finish();
            return;
        }

        TrashesData trashesData = trashHandler.getTrashesData();
        if (trashesData == null) {
            finish();
            return;
        }

        if (mType == VIDEO) {
            trashItems = trashesData.getTrashesByType(TrashType.VIDEO_FILE);
        } else if (mType == LARGE) {
            trashItems = trashesData.getTrashesByType(TrashType.LARGE_FILE);
        }

        if (trashItems == null || trashItems.isEmpty()) {
            finish();
            return;
        }

        //初始化勾选状态
        for (TrashItem item : trashItems) {
            item.isSelected = false;
        }
        mAdapter = new VideoLargeFileAdapter(VideoLargeFileActivity.this, trashItems, mType);
        mListView.setAdapter(mAdapter);

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TrashItem item = (TrashItem) parent.getAdapter().getItem(position);
                showDeleteDialog(item);
            }
        });

        mAdapter.setDeleteCallback(new DeepAdapter.OnDeleteCallback() {
            @Override
            public void onClick(int position, TrashItem item) {
                if (item.isSelected) {
                    mDeleteItemCount++;
                    mDeleteItemSize += item.size;
                } else {
                    mDeleteItemCount--;
                    mDeleteItemSize -= item.size;
                }

                setDeleteButton(mDeleteBtn);
            }
        });

        mDeleteBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogInfo info = new DialogInfo();
                info.setSize(mDeleteItemSize).setCount(mDeleteItemCount + "");
                showDeleteDialog(info);
            }
        });
    }

    @Override
    protected void onDelete() {
        List<TrashItem> deleteList = new ArrayList<TrashItem>();
        for (TrashItem item : trashItems) {
            if (item.isSelected) {
                deleteList.add(item);
            }
        }

        if (!deleteList.isEmpty()) {
            trashItems.removeAll(deleteList);
            mAdapter.notifyDataSetChanged();

            delete(deleteList);
            if (trashItems.isEmpty()) {
                onBackPressed();
                ToastHelper.create(getApplicationContext(), R.string.trash_delete_success,
                        Toast.LENGTH_LONG).show();
            }

            mDeleteItemCount = 0;
            mDeleteItemSize = 0;

            setDeleteButton(mDeleteBtn);
        }
    }

    @Override
    protected void delete(final List<TrashItem> items) {
        ThreadPool.runOnPool(new Runnable() {
            @Override
            public void run() {

                if (mType == VIDEO) {
                    MediaHelper.getHelper(getContentResolver()).deleteMediaVideo(items);
                } else {
                    MediaHelper.getHelper(getContentResolver()).deleteLargeFile(items);
                }

                for (TrashItem trashItem : items) {
                    if (!TextUtils.isEmpty(trashItem.filePath)) {
                        File deleteFile = new File(trashItem.filePath);
                        deleteFile.delete();
                    }
                }
            }
        });
    }

    protected void showDeleteDialog(final TrashItem item) {

        if (mVideoLargeDialog == null) {
            mVideoLargeDialog = new CommonDialog(VideoLargeFileActivity.this);
            View v =
                    LayoutInflater.from(VideoLargeFileActivity.this).inflate(R.layout.common_video_large_dialog, null);
            mVideoLargeDialog.setContentView(v);
            mPathText = v.findViewById(R.id.path);
            mSizeText = v.findViewById(R.id.size);
            mTimeText = v.findViewById(R.id.time);
        }
        mVideoLargeDialog.setTitle(R.string.common_details);
        if (mType == VIDEO) {
            mVideoLargeDialog.setCancelBtn(R.string.common_cancel, null);
            mVideoLargeDialog.setOkBtn(R.string.trash_video_play, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openFile(item.filePath);
                }
            });
            mTimeText.setText(
                    Html.fromHtml(getString(R.string.trash_clean_duration, ((VideoTrashItem) item).mDuration)));
        } else {
            mTimeText.setText(Html.fromHtml(
                    getString(R.string.trash_clean_date,
                            DateTimeUtils.formatDate(((FileTrashItem) item).lastModified))));
            mVideoLargeDialog.setOkBtn(R.string.common_ok, null);
        }
        mPathText.setText(Html.fromHtml(getString(R.string.trash_clean_path, item.filePath)));
        mSizeText.setText(Html.fromHtml(getString(R.string.trash_clean_size, StringUtils.getSizeString(item.size))));

        mVideoLargeDialog.show();
    }

    // 根据文件类型，运行文件
    private void openFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }

        File file = new File(path);
        if (!file.exists()) {
            return;
        }

        Uri data;
        Intent intent = new Intent(android.content.Intent.ACTION_VIEW);

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            data = FileProvider.getUriForFile(imContext, imContext.getPackageName(), file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            data = Uri.fromFile(file);
        }

        String type = MimeTypeUtil.getMimeType(file.getName());
        if (!TextUtils.isEmpty(type)) {
            intent.setDataAndType(data, type);
        }

        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            ToastHelper.create(this, R.string.application_not_available, Toast.LENGTH_SHORT).show();
        }
    }
}
